//
//  HBEmotionToolBarView.swift
//  sinaWeibo
//
//  Created by Beans on 16/7/2.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

//class HBEmotionToolBarView: UIView {
//
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        setupUI()
//    }
//
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//
//    private func setupUI() {
//        backgroundColor = color_HSB_Random()
//
//    }
//
//}


protocol HBEmotionToolBarViewDelegate: NSObjectProtocol {
    func emotionButtonClick(type: HBEmotionType)
}

enum HBEmotionType: Int {
    case Recent = 1000
    case Default = 1001
    case Emoji = 1002
    case Lxh = 1003
}

// 适配iOS9之后的UIStackView
class HBEmotionToolBarView: UIStackView {

    // 设置代理属性
    weak var delegate: HBEmotionToolBarViewDelegate?

    // 定义按钮, 记录
    var currentButton: UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()

        // 需要设置2个属性 (方向, 填充方式)
        axis = .Horizontal
        distribution = .FillEqually
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = color_HSB_Random()

        addChildButtons("最近", type: .Recent)
        addChildButtons("默认", type: .Default)
        addChildButtons("emoji", type: .Emoji)
        addChildButtons("浪小花", type: .Lxh)
    }

    private func addChildButtons(title: String, image: String = "compose_emotion_table", type: HBEmotionType) {
        let button = UIButton()
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        button.setBackgroundImage(UIImage(named: "\(image)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "\(image)_selected"), forState: .Selected)
        // 事件
        button.addTarget(self, action: "childButtonClick:", forControlEvents: .TouchUpInside)
        // tag设为`枚举值` (type.rawValue获取)
        button.tag = type.rawValue
        // 添加到UIStackView
        addArrangedSubview(button)

        // 设置默认选中的按钮
        if type == .Default {
            button.selected = true
        }
    }

    @objc private func childButtonClick(button: UIButton) {

        // (法一)
//        // 判断 点击同一个button, 返回
//        if button == currentButton {
//            return
//        }
//        currentButton?.selected = false
//        button.selected = true
//        currentButton = button

        // (法二)
        for subview in subviews {
            let subButton = subview as! UIButton
            subButton.selected = false
        }
        button.selected = true

        // 调用代理
        delegate?.emotionButtonClick(HBEmotionType(rawValue: button.tag)!)
    }

    // MARK: - lazy load
}